package com.atguigu.chapter05.source;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.SourceFunction;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/7/16 14:35
 */
public class Flink04_Source_Custom {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(2);
    
        env.addSource(new MySource("hadoop162", 9999)).print();
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    // 从Socket 读取数据, 数据是水位传感器采集到的数据
    // sensor_1,10000,10
    //pojo bean
    public static class MySource implements SourceFunction<WaterSensor> {
        private String host;
        private int port;
        private boolean isCancel;
    
        public MySource(String host, int port) {
            this.host = host;
            this.port = port;
        }
        
        // 用来生产数据, 放入到流中
        @Override
        public void run(SourceContext<WaterSensor> ctx) throws Exception {
            // 实现从socket读取数据
            Socket socket = new Socket(host, port);
            InputStream is = socket.getInputStream();
            // 把字节
            // 流转成字符流
            InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
            BufferedReader read = new BufferedReader(isr);
            String line = read.readLine();
            while (!isCancel && line != null) {
                // 把读到的一行数据, 放入流中
                // sensor_1,10000,10
                String[] data = line.split(",");
    
                ctx.collect(new WaterSensor(data[0], Long.valueOf(data[1]), Integer.valueOf(data[2])));
                line = read.readLine();
            }
        }
        
        // 调用这个方法, 停止source
        @Override
        public void cancel() {
            this.isCancel = true;
        }
    }
}
